package cn.stylefeng.guns.modular.system.controller;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.modular.dto.UserDTO;
import cn.stylefeng.guns.modular.system.entity.AppUserInfo;
import cn.stylefeng.guns.modular.system.entity.AppUserInfoRes;
import cn.stylefeng.guns.modular.system.enums.ResultEnum;
import cn.stylefeng.guns.modular.system.enums.TestEnum;
import cn.stylefeng.guns.modular.system.exception.ProjectException;
import cn.stylefeng.guns.modular.system.service.AppUserInfoService;
import cn.stylefeng.guns.modular.system.service.ProxyUserService;
import cn.stylefeng.guns.modular.system.utils.ResultVOUtil;
import cn.stylefeng.guns.modular.system.vo.ResultVO;
import cn.stylefeng.guns.modular.system.vo.TestEnumVO;
import cn.stylefeng.guns.modular.system.vo.UserInfoVO;
import cn.stylefeng.guns.sys.core.exception.enums.BizExceptionEnum;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.roses.core.util.MD5Util;
import cn.stylefeng.roses.kernel.model.exception.RequestEmptyException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName AppUserInfoController
 * @Author lzy
 * @Date 2020/1/11 16:03
 * @VERSION 1.0
 **/
@Controller
@RequestMapping("/appUserInfo")
public class AppUserInfoController {

    private final static Logger log = LoggerFactory.getLogger(ProxyUserController.class);
    private static final String SECCESS = "SECCESS";

    @Autowired
    private AppUserInfoService appUserInfoService;
    @Autowired
    private ProxyUserService proxyUserService;

    private String PREFIX = "/modular/system/appUser/";


    /**
     * 跳转到主页面
     *
     * @author wg
     * @Date 2019-06-20
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "appUser.html";
    }

    /**
     * 跳转添加页面
     *
     * @author wg
     * @Date 2019-06-20
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "appUser_add.html";
    }

    /**
     * 跳转修改详情
     *
     * @author wg
     * @Date 2019-06-20
     */
    @RequestMapping("/editDetails")
    public String editDetails() {
        return PREFIX + "appUser_edit_details.html";
    }

    /**
     * 跳转修改费率
     *
     * @author wg
     * @Date 2019-06-20
     */
    @RequestMapping("/editRate")
    public String editRate() {
        return PREFIX + "appUser_edit_rate.html";
    }

    /**
     * 个人用户列表
     * @param startTime
     * @param endTime
     * @param account
     * @param phone
     *           当前代理的id，做为where条件只查询当前所属代理开启的用户
     * @param pageNum
     * @return
     */
    @RequestMapping("/selectUserInfoList")
    @ResponseBody
    public ResultVO selectUserInfoList(@RequestParam(value = "startTime", required = false) String startTime,
                                       @RequestParam(value = "endTime", required = false)String endTime,
                                       @RequestParam(value = "account", required = false)String account,
                                       @RequestParam(value = "name", required = false)String phone,
                                       @RequestParam("page")Integer pageNum, @RequestParam("limit") Integer pageSize){
        Long id = LoginContextHolder.getContext().getUserId();
        log.info("查询id为：" +  id + " 代理的下级用户 " );
        Assert.isTrue(!ObjectUtils.isEmpty(id), ResultEnum.PROXYID_DOES_NOT_EXIST.getMessage());
        Assert.isTrue(!ObjectUtils.isEmpty(pageNum),ResultEnum.PLEASE_SET_PAGINATION_PARAMETERS.getMessage());
        //查询所有的子代理
        List<String> subUserIds = proxyUserService.findSubUserIdList(id.toString());
        //查询用户代理中加入自己的id
        subUserIds.add(id.toString());
        //设置默认分页参数
        PageHelper.startPage(pageNum,pageSize);
        List<AppUserInfoRes> list = appUserInfoService.findAppUserInfo(startTime,endTime,account,phone,subUserIds);
        PageInfo<AppUserInfoRes> pageInfo = new PageInfo<>(list);
        List<AppUserInfoRes> appUserInfos = pageInfo.getList();
        return ResultVOUtil.success(appUserInfos,pageInfo.getTotal());
    }

    /**
     * 代理创建用户，只要是代理后台的用户都能创建用户，并且可以设置费率
     * @return
     */
    @RequestMapping("/createUser")
    @ResponseBody
    public ResultVO createUser(UserInfoVO userInfoVO){
        //通过session获取当前登录的用户的ID
        Long superiorAgentId = LoginContextHolder.getContext().getUserId();
        log.info("代理创建用户-----手机号：" + userInfoVO.getPhone());
        log.info("代理创建用户-----代理id："+ superiorAgentId);
        log.info("代理创建用户-----邮箱：" + userInfoVO.getEmail());
        //必须要有创建者（代理）的id
        Assert.isTrue(!ObjectUtils.isEmpty(superiorAgentId),ResultEnum.PROXYID_DOES_NOT_EXIST.getMessage());
        userInfoVO.setProxyId(superiorAgentId);
        //查看代理表是否有此代理，目的为区分是否为用户还是代理
        User user = appUserInfoService.selectUserById(superiorAgentId);
        Assert.isTrue(!ObjectUtils.isEmpty(user),ResultEnum.PROXY_DOSE_NOT_EXIST.getMessage());
        //TODO 判断账号(phone)是否重复
        Integer userCount = appUserInfoService.getAccountCount(userInfoVO.getPhone());
        if( userCount != 0){
            //该用户已经注册或在审批
            log.info("手机号重复了====phone="+userInfoVO.getPhone());
            throw new RequestEmptyException(BizExceptionEnum.USER_ALREADY_REG.getMessage());
        }
        //TODO 判断邮箱(email)是否重复
        Integer emailCount = appUserInfoService.getEmailCount(userInfoVO.getEmail());
        if( emailCount != 0){
            //该用户已经注册或在审批
            log.info("邮箱重复了====email="+userInfoVO.getEmail());
            throw new RequestEmptyException(BizExceptionEnum.USER_ALREADY_REG.getMessage());
        }
        log.info(superiorAgentId + "：代理用户添加app用户");
        log.info(userInfoVO.toString());
        appUserInfoService.insertUser(userInfoVO);
        return ResultVOUtil.success(SECCESS);
    }

    /**
     * 修改用户的信息和密码
     * @param userInfoVO 修改信息
     * @param appUserId 被修改的用户id
     * @return
     */
    @RequestMapping("/updateUser")
    @ResponseBody
    public ResultVO updateUser(UserInfoVO userInfoVO,
                               @RequestParam("id") Long appUserId){
        Long superiorAgentId = LoginContextHolder.getContext().getUserId();
        AppUserInfo appUserInfo = appUserInfoService.selectAppUserInfo(appUserId);
        if(!ObjectUtils.isEmpty(userInfoVO.getPhone())){
            //如果电话为空就使用user里面的电话,如果不为空的话就覆盖一下
            appUserInfo.setPhone(userInfoVO.getPhone());
        }

        if(!ObjectUtils.isEmpty(userInfoVO.getEmail())){
            appUserInfo.setEmail(userInfoVO.getEmail());
        }
        //判断是否有上下级关系
//        if (superiorAgentId != appUserInfo.getProxyId()){
//            throw new RequestEmptyException(ResultEnum.UPDATE_PROXY_DOSE_NOT_EXIST.getMessage());
//        }
        // + appUserInfo.getEmail() + appUserInfo.getPhone() + "RecruitmentInformation"
        String newPassword = MD5Util.encrypt(MD5Util.encrypt(userInfoVO.getUserPwd()));
        UserDTO build = UserDTO.builder()
                .id(appUserId)
                .account(userInfoVO.getAccount())
                .email(userInfoVO.getEmail())
                .idCard(userInfoVO.getIdCard())
                .nickName(userInfoVO.getNickName())
                .phone(userInfoVO.getPhone())
                .realName(userInfoVO.getRealName())
                .registerTime(new Date())
                .userPwd(newPassword)
                .build();
        log.info(superiorAgentId + "：代理用户修改ID："+ appUserId + "app用户信息");
        log.info(build.toString());
        appUserInfoService.updateAppUserInfo(build);
        return ResultVOUtil.success(SECCESS);
    }

    /**
     * 修改用户的费率
     * @param exchangeRate 费率
     * @param  appUserId 用户的id
     * @return
     */
    @RequestMapping("/updateRate")
    @ResponseBody
    public ResultVO updateRate(@RequestParam("exchangeRate") BigDecimal exchangeRate,
                               @RequestParam("id") Long appUserId) throws Exception {
        Long superiorAgentId = LoginContextHolder.getContext().getUserId();
        //当前代理
        User user = proxyUserService.selectUserById(superiorAgentId);
        //需要修改的用户
        AppUserInfo appUser = appUserInfoService.selectAppUserInfo(appUserId);

        Assert.isTrue(!ObjectUtils.isEmpty(user),ResultEnum.PROXY_DOSE_NOT_EXIST.getMessage());
        Assert.isTrue(!ObjectUtils.isEmpty(appUser),ResultEnum.UPDATE_PROXY_DOSE_NOT_EXIST.getMessage());
        //判断是否有上下级关系
//        if (!superiorAgentId.equals(appUser.getProxyId())){
//            throw new RequestEmptyException(ResultEnum.UPDATE_PROXY_DOSE_NOT_EXIST.getMessage());
//        }

        //TODO 修改费率之后，如果当前代理下面的代理或者用户比修改之后的费率高，那么报错并且给出详细信息到前端
            if (user.getExchangeRate().compareTo(exchangeRate) != 1) {
                //如果旗下代理的费率大于本代理修改的费率，就直接报错给前端详细错误信息
                //第一，修改我下级用户费率不能高于我
//                return USER_ERROR;
                return ResultVOUtil.error(new ProjectException("当前下级用户费率高于本代理"));
            }
        log.info(superiorAgentId + "：代理用户修改ID："+ appUserId + "app用户费率为：" +exchangeRate);
        appUserInfoService.updateRate(appUser.getId(),exchangeRate);
        return ResultVOUtil.success(SECCESS);
    }

    //查询appUser详情
    @RequestMapping("/selectAppUserInfo")
    @ResponseBody
    public ResultVO selectAppUserInfo(@RequestParam("appUserId") Long appUserId){
        Assert.isTrue(!ObjectUtils.isEmpty(appUserId),ResultEnum.NO_MANDATORY_FIELDS.getMessage());
        AppUserInfo appUserInfo = appUserInfoService.selectAppUserInfo(appUserId);
        return ResultVOUtil.success(appUserInfo);
    }

    /**
     * 删除用户
     * @return
     */
    @RequestMapping("/deleteUserInfo")
    @ResponseBody
    public ResultVO deleteUserInfo(@RequestParam("appUserId") Long appUserId){
        Long superiorAgentId = LoginContextHolder.getContext().getUserId();

        Assert.isTrue(!ObjectUtils.isEmpty(superiorAgentId),ResultEnum.PROXYID_DOES_NOT_EXIST.getMessage());
        Assert.isTrue(!ObjectUtils.isEmpty(appUserId),ResultEnum.PROXYID_DOES_NOT_EXIST.getMessage());

        AppUserInfo appUser = appUserInfoService.selectAppUserInfo(appUserId);
        //判断是否有上下级关系
//        if (superiorAgentId != appUser.getProxyId()){
//            throw new RequestEmptyException(ResultEnum.UPDATE_PROXY_DOSE_NOT_EXIST.getMessage());
//        }
        log.info(superiorAgentId + "：代理用户删除ID："+ appUserId + "app用户");
        appUserInfoService.deleteUserInfo(appUserId);
        return ResultVOUtil.success(SECCESS);
    }

    @RequestMapping("/testEnum")
    @ResponseBody
    public ResultVO testEnum(TestEnumVO testEnumVO){
        System.out.println(testEnumVO.getTestEnum().getMsg());
        return ResultVOUtil.success(testEnumVO);
    }
}
